/*
 * @(#)XmlGenerater.java		       version: 0.1 
 * Date:2012-2-10
 *
 * Copyright (c) 2011 CFuture09, Institute of Software, 
 * Guangdong Ocean University, Zhanjiang, GuangDong, China.
 * All rights reserved.
 */
package com.sinaapp.msdxblog.tools.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

/**
 * @author Geek_Soledad (66704238@51uc.com)
 */
public class JiongXmlGenerator {

	public static final String ROOT = "resource";
	public static final String ID_ATTRIBUTE = "id";
	public static final String CONTENT = "content";

	public String resString;
	public String[] resSplits;

	/**
	 * 读取原文件
	 * 
	 * @param path
	 */
	public void readFile(String path) {
		File file = new File(path);
		try {
			resString = FileUtils.readFileToString(file, "gbk");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void splieResString() {
//		resSplits = resString.split("\\d+、");
//		resSplits = resString.split("\\d+\\.(?=\\D)");
		resSplits = resString.split("\\[1.\\]");
	}

	/**
	 * 生成xml文件在指定路径上。
	 * @param outPath
	 */
	public void generateXml(String outPath) {
		Element root = new Element(ROOT);
		createChild(root);
		XMLOutputter outputter = new XMLOutputter();
		Document doc = new Document(root);
		try {
			outputter.output(doc, new FileOutputStream(new File(outPath)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void createChild(Element root) {
		for (int i = 1, length = resSplits.length; i < length; i++) {
			Element content = new Element(CONTENT);
			Attribute id = new Attribute(ID_ATTRIBUTE, i + "");
			content.setAttribute(id);
			content.setText(resSplits[i].replace("\r", ""));
			root.addContent(content);
		}
	}

	public final void generateXmlByPath(String path) {
		readFile(path);
		splieResString();
		generateXml(getResultPath(path));
	}
	
	public final String getResultPath(String path) {
		return path.substring(0, path.lastIndexOf(".")) + ".xml";
	}
	
	public static void main(String[] args) {
		JiongXmlGenerator generator = new JiongXmlGenerator();
//		generator.readFile("E:/androidApk/textRes/jiong/jiong.txt");
//		generator.readFile("E:/androidApk/textRes/jiong/jiong2.txt");
//		generator.readFile("E:/androidApk/2012/02/一日一囧/情人节冷笑话/qrj.txt");
		generator.generateXmlByPath("E:/androidApk/2012/02/一日一囧/第3期/jiong1.txt");
	}
}
